import { useModel } from '@umijs/max';
import { ColorPicker, FloatButton, Image, Spin } from 'antd';
import { openDB } from 'idb';
import { useEffect, useMemo, useState } from 'react';
import PageFlip from 'react-pageflip';
import styles from './index.less';
// 初始化 IndexedDB
const dbPromise = openDB('ImageStorage', 1, {
  upgrade(db) {
    db.createObjectStore('dataSource');
  },
});

const bgColorList = [
  {
    name: '象牙色',
    value: '#FFFFF0',
  },
  {
    name: '奶油色',
    value: '#FFFDD0',
  },
  {
    name: '亚麻色',
    value: '#FAF0E6',
  },
  {
    name: '古董白色',
    value: '#FAEBD7',
  },
  {
    name: '浅黄色',
    value: '#F5F5DC',
  },
  {
    name: '纸张色',
    value: '#FFF9E6',
  },
  {
    name: '默认',
    value: '#fff',
  },
];

const HomePage = () => {
  const { name } = useModel('global');
  const [dataSource, setDataSource] = useState([]);
  const [bgBoxColor, setBgBoxColor] = useState('#FFF9E6');

  useEffect(() => {
    // let data = localStorage.getItem('dataSource');
    // setDataSource(JSON.parse(data));
    loadFilesFromCache();
  }, []);

  const loadFilesFromCache = async () => {
    const db = await dbPromise;
    const cachedFiles = await db.getAll('dataSource');
    setDataSource(cachedFiles);
    // return cachedFiles;
  };

  const content = useMemo(() => {
    return dataSource?.map((item, index) => {
      return (
        <div key={item.id} className={styles.itemBox}>
          <div style={{ backgroundColor: bgBoxColor, height: '100%' }}>
            <div className={styles.itemTitle}>{item.title}</div>
            <div className={styles.itemImg}>
              <Image width={400} preview={false} src={item.url} />
            </div>
            <div className={styles.itemContent}>
              <div className={styles.itemDec}>{item.dec}</div>
              <div style={{ color: bgBoxColor }}>{bgBoxColor}</div>
            </div>
          </div>
        </div>
      );
    });
  }, [bgBoxColor, dataSource]);

  return (
    <div className={styles.container}>
      <div style={{ display: 'flex', alignItems: 'center' }}>
        <div style={{ marginRight: '12px' }}>背景颜色切换</div>
        <ColorPicker
          defaultValue="#FFF9E6"
          onChange={(value, color) => {
            setBgBoxColor(color);
          }}
        />
      </div>
      <Spin spinning={dataSource.length === 0}>
        <PageFlip
          width={600}
          height={700}
          startPage={0}
          size={'fixed'} // 书籍是否在父元素下拉伸
          minWidth={0}
          maxWidth={1000}
          minHeight={0}
          maxHeight={1000}
          drawShadow={true} // 翻页时是否绘制阴影
          flippingTime={1000} // 翻转动画时间
          usePortrait={true} // 启用切换到纵向模式
          startZIndex={0} // z-index 的初始值
          autoSize={true} // 父元素将等于书籍的大小
          maxShadowOpacity={1} // 阴影强度（1：最大强度，0：隐藏阴影）
          showCover={true} // 则第一页和最后一页将被标记为硬页并以单页模式显示
          mobileScrollSupport={true} // 在移动设备上触摸书籍时禁用内容滚动
          clickEventForward={true} // 将点击事件转发给页面子 html 元素（仅适用于a和button标签）
          useMouseEvents={true} // 使用鼠标和触摸事件来翻页
          swipeDistance={30} // 检测滑动的最小距离
          showPageCorners={false}
          disableFlipByClick={false}
        >
          {content}
        </PageFlip>
      </Spin>
      <FloatButton.Group
        trigger="click"
        type="primary"
        style={{
          insetInlineEnd: 94,
        }}
        icon=""
        description="背景"
      >
        {bgColorList?.map((item, index) => {
          return (
            <FloatButton
              description={item.name}
              onClick={() => {
                setBgBoxColor(item.value);
              }}
              key={index}
            >
              {item.name}
            </FloatButton>
          );
        })}
      </FloatButton.Group>
    </div>
  );
};

export default HomePage;
